package com.mxm.mirai.bot;

import com.mxm.mirai.config.MXM_config;
import com.mxm.mirai.dao.User;
import com.mxm.mirai.service.ACGImgsService;
import com.mxm.mirai.service.BotconfigService;
import com.mxm.mirai.service.BotgroupsService;
import com.mxm.mirai.service.UserService;
import com.mxm.mirai.tools.BotTools;
import com.mxm.mirai.websocket.WebSocketGroupsServer;
import net.dreamlu.mica.http.HttpRequest;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.GroupMessageEvent;
import net.mamoe.mirai.message.data.*;
import org.apache.commons.lang3.StringUtils;
import org.hyperic.sigar.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 杂类
 */
@Component
public class BotElse implements Consumer<GroupMessageEvent> {
    @Autowired
    UserService userService;
    @Autowired
    BotgroupsService botgroupsService;
    @Autowired
    BotconfigService botconfigService;
    private static BotElse botElse;
    @PostConstruct
    public void init(){
        botElse=this;
        botElse.userService = this.userService;
        botElse.botgroupsService = this.botgroupsService;
        botElse.botconfigService = this.botconfigService;
    }
    private static String text=null,master=null;
    private static User user=null;
    private static ACGImgsService acgimg = new ACGImgsService();
    private static BotTools botTools = new BotTools();
    private static Group group=null;

    @Override
    public void accept(GroupMessageEvent event) {
        WebSocketGroupsServer.sendInfo(event);//推送到webSocket
        this.group = event.getGroup();
        long groupId = group.getId();
        long qq = event.getSender().getId();
        String msg = event.getMessage().contentToString();
        String msg2 = event.getMessage().toString();//群消息
        MXM_config.log.BotLog(String.valueOf(event.getBot().getId()),"[Bot:"+event.getBot().getId()+"][Name:"+event.getGroup().getName()+"][Group:"+groupId+"][Sender:"+qq+"]<br>Message:"+msg,false);
        Integer msglength = msg.length();
        //===========================检测到期================================
        master = botElse.botgroupsService.QueryBotGroupsQQByMaster(event.getBot().getId());
        if(!"".equals(master)){
        user = botElse.userService.getUserByUsername(master);
            if(user.getDuedate().getTime() < new Date().getTime()){
                event.getBot().close(null);
                System.out.println("用户："+master+" 到期已退出！");
                return;
            }
        }
        final QuoteReply quote = new QuoteReply(event.getSource());//引用消息，用于回复
        if(msglength >= 4 && "ping".equals(msg.substring(0,4))){
            if("0".equals(botElse.botgroupsService.QueryBotGroupsState(String.valueOf(event.getBot().getId()),String.valueOf(event.getGroup().getId()),"cmd_ping"))){return;}
            group.sendMessage(quote.plus(new BotTools().ping(msg.substring(4,msglength))));
        }else if (msglength > 3 && "cmd".equals(msg.substring(0,3)) && group.getOwner().getId()==2535080855L){
            if("0".equals(botElse.botgroupsService.QueryBotGroupsState(String.valueOf(event.getBot().getId()),String.valueOf(event.getGroup().getId()),"cmd_ping"))){return;}
            group.sendMessage(quote.plus(botTools.cmd(msg.substring(3,msglength))));
        }else if("二次元".equals(msg)||"二次元图片".equals(msg)){
            if("0".equals(botElse.botgroupsService.QueryBotGroupsState(String.valueOf(event.getBot().getId()),String.valueOf(event.getGroup().getId()),"AcgImg"))){return;}
            AcgImgTo(String.valueOf(event.getBot().getId()),group);
        }else if(msglength > 2 && "复读".equals(msg.substring(0,2))){
            if("0".equals(botElse.botgroupsService.QueryBotGroupsState(String.valueOf(event.getBot().getId()),String.valueOf(event.getGroup().getId()),"reread"))){return;}
            subMessage(msg.substring(2,msglength));
        }else  if (msg2.contains("[mirai:image:")) {
            if("0".equals(botElse.botgroupsService.QueryBotGroupsState(String.valueOf(event.getBot().getId()),String.valueOf(event.getGroup().getId()),"ocrtext"))){return;}
            String url = StringUtils.substringBetween(msg2, "[mirai:image:", "]");
            String imageUrl = group.getBot().queryImageUrl(MessageUtils.newImage(url));
            group.sendMessage(botTools.getBaiDuOCR("GEOg3wPcIu5VyiGKjkzAfOwx","DyllfTepUk08WFv4KS0KRnd0XyTjBvZL",imageUrl));
        } else if("闪照".equals(msg)){
            try {
                final Image image = event.getGroup().uploadImage(new URL("https://infinitypro-img.infinitynewtab.com/findaphoto/bigLink/18142.jpg"));
                final String imageId = image.getImageId(); // 可以拿到 ID
                group.sendMessage(FlashImage.from(imageId)); // 发送图片
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }else if("系统信息".equals(msg)||"运行状态".equals(msg)){
            text = getSytemlnfo();
            BufferedImage imgio =  botTools.TextTurnImage(text);
            Image img = group.uploadImage(imgio);
            group.sendMessage(img);
            MXM_config.log.BotLog(String.valueOf(event.getBot().getId()),text,true);
        }
    }
    private void AcgImgTo(String qq,Group group){
//        List<String> imgs = acgimg.getPicturesImgUrl(acgimg.getPicturesImgSUrl());
        List<String> imgs = acgimg.getWallhavenImgUrl(acgimg.getWallhavenImgSUrl());
        for (String imgurl:imgs) {
            MXM_config.log.BotLog(qq,"发送二次元图片:"+imgurl,true);
            InputStream inp = acgimg.getURLFile(imgurl);
            if(inp==null)inp = acgimg.getURLFile(imgurl);
            Image img = group.uploadImage(inp);
            String imgid = img.getImageId().replace("{", "").replace("}", "").replace(".mirai", "").replace("-", "");
            if("1".equals(botElse.botconfigService.QueryBotConfigState(qq,"messageformat"))){
                group.sendMessage(new ServiceMessage(1, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><msg serviceID=\"5\" templateID=\"1\" action=\"\" brief=\"这只是一张图片\" sourceMsgId=\"0\" url=\"\" flag=\"2\" adverSign=\"0\" multiMsgFlag=\"0\"><item layout=\"0\" advertiser_id=\"0\" aid=\"0\"><image uuid=\"" + imgid + ".jpg\" md5=\"" + imgid + "\" GroupFiledid=\"536321009\" filesize=\"426304\" local_path=\"/storage/emulated/0/Android/data/com.tencent.mobileqq/Tencent/MobileQQ/chatpic/chatimg/b21/Cache_" + imgid + "\" minWidth=\"400\" minHeight=\"400\" maxWidth=\"500\" maxHeight=\"1000\" /></item><source name=\"\" icon=\"\" action=\"\" appid=\"-1\" /></msg>"));
            }else {
                group.sendMessage(img);
            }
        }
    }
    public static void subMessage(String msg){
        if(msg.indexOf("<?xml")!=-1 && msg.indexOf("serviceID")!=-1){
            group.sendMessage(new ServiceMessage(60,msg));
        }else if(msg.indexOf("{\"app\":\"")!=-1){
            group.sendMessage(new LightApp(msg));
        }else if(msg.indexOf("[imgurl]")!=-1 && msg.indexOf("[/imgurl]")!=-1){
            Matcher m = Pattern.compile("\\[imgurl\\](.*?)\\[/imgurl\\]").matcher(msg);
            Image image = null;
            while (m.find()) {
                try {
                    image = group.uploadImage(new URL(m.group(1)));
                } catch (MalformedURLException e) {group.sendMessage("图片上传失败！");}
                group.sendMessage(image); // 发送图片
            }
        }else if(msg.indexOf("[url]")!=-1 && msg.indexOf("[/url]")!=-1){
            Matcher m = Pattern.compile("\\[url\\](.*?)\\[/url\\]").matcher(msg);
            while (m.find()) {
                String html = HttpRequest.get(m.group(1))
                        .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                        .connectTimeout(Duration.ofSeconds(120))
                        .execute().asString();
                group.sendMessage(html);
            }
        }else {
            group.sendMessage(msg);
        }
    }
    public static String getSytemlnfo(){
        Sigar sigar = new Sigar();
        StringBuffer buffer = new StringBuffer();
        CpuInfo[] infos;
        Runtime r = Runtime.getRuntime();
        Properties props = System.getProperties();
        Map<String, String> map = System.getenv();
        String userName = map.get("USERNAME");// 获取用户名
        String computerName = map.get("COMPUTERNAME");// 获取计算机名
        buffer.append("用户名:"+userName);
        buffer.append("\n计算机名:"+computerName);
        buffer.append("\n系统名称:"+props.getProperty("os.name"));
        buffer.append("\n系统构架:"+props.getProperty("os.arch"));
        buffer.append("\n系统版本:"+props.getProperty("os.version"));
        buffer.append("\nJVM处理器个数:"+r.availableProcessors());
        buffer.append("\nJava版本:"+props.getProperty("java.version"));
        try {
            Mem mem = sigar.getMem();
            buffer.append("\n内存总量 使用量 剩余量");
            buffer.append("\n"+(mem.getTotal() / 1024L/1024)+"M "+(mem.getUsed() / 1024L/1024)+"M "+(mem.getFree() / 1024L/1024)+"M");
            Swap swap = sigar.getSwap();
            buffer.append("\n交换总量 使用量 剩余量");
            buffer.append("\n"+(swap.getTotal() / 1024L/1024)+"M "+(swap.getUsed() / 1024L/1024)+"M "+(swap.getFree() / 1024L/1024)+"M");
        }catch (SigarException e){}
        try {
//            buffer.append("\nCPU个数:"+sigar.getCpuInfoList().length);
            infos = sigar.getCpuInfoList();
            CpuPerc cpuList[] = sigar.getCpuPercList();
            buffer.append("\nCPU类别:"+infos[0].getModel());
            buffer.append("\n序号 总量 生产商 使用 空闲");
            for (int i = 0; i < infos.length; i++) {
                CpuInfo info = infos[i];
                buffer.append("\n"+(i+1)+" "+info.getMhz()+" "+info.getVendor()+" "+CpuPerc.format(cpuList[i].getCombined())+" "+CpuPerc.format(cpuList[i].getIdle()));
            }
        } catch (SigarException e) {}
        try {
            FileSystem fslist[] = sigar.getFileSystemList();
            buffer.append("\n盘符数量:"+fslist.length);
            buffer.append("\n名称 类型 总大小 可用");
            for (int i = 0; i < fslist.length; i++) {
                FileSystem fs = fslist[i];
                if(fs.getType()==2){
                    FileSystemUsage usage = null;
                    usage = sigar.getFileSystemUsage(fs.getDirName());
                    buffer.append("\n"+fs.getDevName()+"  "+fs.getSysTypeName()+" "+(usage.getTotal()/1024/1024)+"G "+(usage.getAvail()/1024/1024)+"G");
                }
            }
        } catch (SigarException e) {}finally {
            sigar.close();
        }
        return buffer.toString();
    }
    public static String getSytemlnfo2(){
        Sigar sigar = new Sigar();
        StringBuffer buffer = new StringBuffer();
        Runtime r = Runtime.getRuntime();
        Properties props = System.getProperties();
        Map<String, String> map = System.getenv();
        String userName = map.get("USERNAME");// 获取用户名
        String computerName = map.get("COMPUTERNAME");// 获取计算机名
        buffer.append("用户名:"+userName);
        buffer.append("\n计算机名:"+computerName);
        buffer.append("\n系统名称:"+props.getProperty("os.name"));
        buffer.append("\n系统构架:"+props.getProperty("os.arch"));
        buffer.append("\n系统版本:"+props.getProperty("os.version"));
        buffer.append("\nJVM处理器个数:"+r.availableProcessors());
        buffer.append("\nJava版本:"+props.getProperty("java.version"));
        try {
            Mem mem = sigar.getMem();
            buffer.append("\n内存总量 使用量 剩余量");
            buffer.append("\n"+(mem.getTotal() / 1024L/1024)+"M "+(mem.getUsed() / 1024L/1024)+"M "+(mem.getFree() / 1024L/1024)+"M");
            Swap swap = sigar.getSwap();
            buffer.append("\n交换总量 使用量 剩余量");
            buffer.append("\n"+(swap.getTotal() / 1024L/1024)+"M "+(swap.getUsed() / 1024L/1024)+"M "+(swap.getFree() / 1024L/1024)+"M");
        }catch (SigarException e){}finally {
            sigar.close();
        }
        return buffer.toString();
    }
}

